﻿using AutoMapper;
using Blog.Application.Contract.User;
using Blog.Application.Contract.User.Dto;
using Blog.EntityFrameworkCore;
using Blog.Module;
using Microsoft.EntityFrameworkCore;
using Infrastructure;

namespace Blog.Application.User;

public class UserServer : IUserServer
{
    private readonly BlogDbContext _blogDbContext;
    private readonly IMapper _mapper;

    public UserServer(BlogDbContext blogDbContext, IMapper mapper)
    {
        _blogDbContext = blogDbContext;
        _mapper = mapper;
    }

    /// <summary>
    /// 创建用户
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    /// <exception cref="BusinessExecptions"></exception>
    public async Task CreateUserAsync(CreateUserDto input)
    {

        if (await _blogDbContext.Users.AnyAsync(x => x.UserName == input.UserName))
        {
            throw new BusinessExecptions("用户名已经存在");
        }

        // Mapper 映射
        var data = _mapper.Map<Users>(input);
        data.CreationTime = DateTime.Now;
        // 添加到数据库
        await _blogDbContext.AddAsync(data);
        // 保存操作
        await _blogDbContext.SaveChangesAsync();

    }

    /// <summary>
    /// 登录
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    /// <exception cref="BusinessExecptions"></exception>
    public async Task<UserDto> LoginAsync(LoginDto input)
    {
        var data = await _blogDbContext.Users.FirstOrDefaultAsync(x => x.UserName == input.UserName && x.Password == input.Password);

        if (data == null)
        {
            throw new BusinessExecptions("账号或密码错误");
        }
        var dto = _mapper.Map<UserDto>(data);
        return dto;
    }
}
